﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace TD.Interface.Credits
{
    internal class Character : DrawableGameComponent
    {
        public int Width { get { return Library.Instance[key].Texture.Width; } }
        public int Height { get { return Library.Instance[key].Texture.Height; } }

        public Vector2 Position { get; set; }
        public Color Color { get; set; }

        public List<Effect> Effects { get; set; }
        private SpriteBatch spriteBatch;
        private BlendState blendState;
        private Texture2D texture;
        private Matrix matrix;
        private char key;

        public Character(Game game, char key, BlendState blendState) :
            base(game)
        {
            this.key = key;
            this.Position = Vector2.Zero;
            this.Color = Color.White;
            this.Effects = new List<Effect>();
            this.blendState = blendState;
            this.DrawOrder = 0x08F00000;
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            texture = Library.Instance[key].Texture;
            base.LoadContent();
        }

        public override void Update(GameTime gameTime)
        {
            matrix = Matrix.Identity;
            matrix *= Matrix.CreateTranslation(-(texture.Width >> 1), -(texture.Height >> 1), 0.0f);

            for (int i = 0; i < Effects.Count; i++)
            {
                Effects[i].Update(gameTime);
                matrix *= Effects[i].Matrix;
            }

            matrix *= Matrix.CreateTranslation((texture.Width >> 1) + Position.X, (texture.Height >> 1) + Position.Y, 0.0f);
            matrix *= Matrix.CreateScale(1.0f, 1.0f, 0.0f); // FLATTEN the image.
            
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            spriteBatch.Begin(SpriteSortMode.BackToFront, blendState, null, null, RasterizerState.CullNone, null, matrix);
            spriteBatch.Draw(texture, Vector2.Zero, Color);
            spriteBatch.End();
            
            base.Draw(gameTime);
        }

        public void DrawSolo(GameTime gameTime)
        {
            spriteBatch.Draw(texture, Position, Color);
        }

        public void Reset()
        {
            foreach (Effect efx in Effects)
            {
                efx.Reset();
            }
        }
    }
}
